package com.cml.topicsystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cml.topicsystem.entity.User;
import com.cml.topicsystem.service.UserService;
import com.cml.topicsystem.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * @author cml
 * @create 2021/6/2 13:18
 */
@RestController
@RequestMapping(value = "user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping(value = "/login")
    public R login(@RequestBody User user, HttpServletRequest request){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername())
                .eq("password",user.getPassword())
                .select("id","username");
        User one = userService.getOne(userQueryWrapper);
        if(one != null) request.getSession().setAttribute("user",user.getUsername());
        return one != null ? R.ok().date(one) : R.error().message("登录失败");
    }

    @PostMapping(value = "register")
    public R register(@RequestBody User user){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername())
                .select("id","username");
        User one = userService.getOne(userQueryWrapper);
        if (one != null){
            return R.error().message("账户已注册");
        }

        boolean save = userService.save(user);
        return save ? R.ok().message("注册成功") : R.error().message("注册失败");
    }

    @PutMapping(value = "update")
    public R update(@RequestBody User user){
        boolean update = userService.update(user,new QueryWrapper<User>().eq("username",user.getUsername()));
        return update ? R.ok().message("用户信息修改成功") : R.error();
    }

    @GetMapping(value = "logout")
    public R logout(HttpServletRequest request){
        try {
            request.getSession().removeAttribute("user");
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok().code("30000").message("退出成功");
    }

}
